<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { userApi } from '../api'

const router = useRouter()

// 表单数据
const formData = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  email: '',
  phone: ''
})

// 错误信息
const errorMsg = ref('')
// 加载状态
const loading = ref(false)
// 用户名检查状态
const usernameChecking = ref(false)
const usernameExists = ref(false)

// 检查用户名是否存在
const checkUsername = async () => {
  if (!formData.username) return
  
  usernameChecking.value = true
  usernameExists.value = false
  
  try {
    const res = await userApi.checkUsername(formData.username)
    usernameExists.value = res.data
  } catch (error) {
    console.error('检查用户名出错:', error)
  } finally {
    usernameChecking.value = false
  }
}

// 注册方法
const handleRegister = async () => {
  // 表单验证
  if (!formData.username || !formData.password || !formData.confirmPassword) {
    errorMsg.value = '用户名和密码不能为空'
    return
  }
  
  if (formData.password !== formData.confirmPassword) {
    errorMsg.value = '两次输入的密码不一致'
    return
  }
  
  if (usernameExists.value) {
    errorMsg.value = '用户名已存在，请更换'
    return
  }
  
  // 重置错误信息
  errorMsg.value = ''
  // 设置加载状态
  loading.value = true
  
  try {
    // 调用注册API
    await userApi.register({
      username: formData.username,
      password: formData.password,
      email: formData.email,
      phone: formData.phone
    })
    
    // 注册成功，跳转到登录页
    router.push('/login')
  } catch (error) {
    // 注册失败，显示错误信息
    errorMsg.value = error.message || '注册失败，请稍后重试'
  } finally {
    // 重置加载状态
    loading.value = false
  }
}

// 跳转到登录页面
const goToLogin = () => {
  router.push('/login')
}
</script>

<template>
  <div class="register-container">
    <div class="register-box">
      <h2>注册账号</h2>
      
      <!-- 错误提示 -->
      <div v-if="errorMsg" class="error-message">
        {{ errorMsg }}
      </div>
      
      <!-- 注册表单 -->
      <form @submit.prevent="handleRegister" class="register-form">
        <div class="form-group">
          <label for="username">用户名</label>
          <div class="input-with-status">
            <input 
              type="text" 
              id="username" 
              v-model="formData.username" 
              @blur="checkUsername"
              placeholder="请输入用户名"
              autocomplete="username"
            >
            <div v-if="usernameChecking" class="input-status checking">检查中...</div>
            <div v-else-if="formData.username && usernameExists" class="input-status error">用户名已存在</div>
            <div v-else-if="formData.username && !usernameExists" class="input-status success">用户名可用</div>
          </div>
        </div>
        
        <div class="form-group">
          <label for="password">密码</label>
          <input 
            type="password" 
            id="password" 
            v-model="formData.password" 
            placeholder="请输入密码"
            autocomplete="new-password"
          >
        </div>
        
        <div class="form-group">
          <label for="confirmPassword">确认密码</label>
          <input 
            type="password" 
            id="confirmPassword" 
            v-model="formData.confirmPassword" 
            placeholder="请再次输入密码"
            autocomplete="new-password"
          >
        </div>
        
        <div class="form-group">
          <label for="email">邮箱（选填）</label>
          <input 
            type="email" 
            id="email" 
            v-model="formData.email" 
            placeholder="请输入邮箱"
            autocomplete="email"
          >
        </div>
        
        <div class="form-group">
          <label for="phone">手机号（选填）</label>
          <input 
            type="tel" 
            id="phone" 
            v-model="formData.phone" 
            placeholder="请输入手机号"
            autocomplete="tel"
          >
        </div>
        
        <div class="form-actions">
          <button type="submit" :disabled="loading" class="btn-register">
            {{ loading ? '注册中...' : '注册' }}
          </button>
          <button type="button" @click="goToLogin" class="btn-login">
            已有账号？去登录
          </button>
        </div>
      </form>
    </div>
  </div>
</template>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f5f5;
}

.register-box {
  width: 100%;
  max-width: 500px;
  padding: 30px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

h2 {
  text-align: center;
  margin-bottom: 24px;
  color: #333;
}

.error-message {
  background-color: #ffebee;
  color: #d32f2f;
  padding: 10px;
  border-radius: 4px;
  margin-bottom: 16px;
  font-size: 14px;
}

.register-form {
  display: flex;
  flex-direction: column;
}

.form-group {
  margin-bottom: 16px;
}

label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
}

input {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 16px;
  transition: border-color 0.3s;
}

input:focus {
  border-color: #4CAF50;
  outline: none;
}

.input-with-status {
  position: relative;
}

.input-status {
  position: absolute;
  right: 0;
  top: 0;
  padding: 10px 12px;
  font-size: 14px;
}

.input-status.checking {
  color: #2196F3;
}

.input-status.error {
  color: #f44336;
}

.input-status.success {
  color: #4CAF50;
}

.form-actions {
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin-top: 24px;
}

button {
  padding: 12px;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

button:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

.btn-register {
  background-color: #4CAF50;
  color: white;
}

.btn-register:hover:not(:disabled) {
  background-color: #45a049;
}

.btn-login {
  background-color: transparent;
  color: #4CAF50;
  border: 1px solid #4CAF50;
}

.btn-login:hover {
  background-color: rgba(76, 175, 80, 0.1);
}
</style>